<template>
  <!-- （Products2.vue文件）此页方法是用写好的接口文件以分页的形式获取商品列表来加载数据的， -->
  <ul>
    <li v-for="item in list" :key="item._id">
      {{item.name}} ￥{{item.price}}——
      <button @click="buyHandle(item._id)">购买</button>
    </li>
    <!-- <li v-for="item in $store.state.list" :key="item._id">
      {{item.name}} ￥{{item.price}}——
      <button @click="buyHandle(item._id)">购买</button>
    </li>-->
    <keep-alive>
      <button v-show="isShowLoadMore" @click="loaData">加载数据</button>
    </keep-alive>
  </ul>
</template>

<script>
import { getList } from '../services/products'
import { addToCart } from '../services/shopcarts'
// import { mapMutations } from 'vuex'

export default {
  data() {
    return {
      list: [],
      isShowLoadMore: true,
      page: 0
    }
  },
  async created() {
    // const res = await getList(this.page)
    // this.list = res.products
    // console.log(this.list)
  },
  methods: {
    async buyHandle(id) {
      const res = await addToCart(id)
      console.log(res)
    },
    async loaData() {
      this.page++
      const res = await getList(this.page)
      // console.log(res.data) // undefined
      console.log(res)
      this.list = [...this.list, ...res.products]
    }
    /* loaData() {
      if (this.$store.state.pages < this.$store.state.page) {
        this.isShowLoadMore = false
        return
      }
      this.$store.dispatch('loadData', { page: this.$store.state.page })
    } */
  }
}
</script>

<style scoped>
ul {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  width: 100%;
}
ul li {
  flex: 1;
  flex-direction: row;
  height: 50px;
  display: flex;
  padding: 0.1rem 0.2rem;
}
button {
  width: 100px;
}
</style>
